"use client"
import React, { useEffect, useState } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,

    Table,
    TableProps, Tag,

} from 'antd';
import { DeleteOutlined, } from "@ant-design/icons";
import { delLogininfor, logininforList } from "@/clientApi/system/monitor/logininfor";
import { setKeyUtils } from "@/utils/Z";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
import { useConfirmModal } from "@/utils/ConfirmModal";

const LoginInfoView: React.FC = () => {
    const { confirm } = useConfirmModal();
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        ipaddr: undefined,
        userName: undefined,
        status: undefined,
    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [dataList, setDataList] = useState<DataType[]>([]);

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '访问编号',
            dataIndex: 'infoId',
            key: 'infoId',
            align: 'center'
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center'
        }, {
            title: '地址',
            dataIndex: 'ipaddr',
            key: 'ipaddr',
            align: 'center'
        }, {
            title: '登录地点',
            dataIndex: 'loginLocation',
            key: 'loginLocation',
            align: 'center'
        }, {
            title: '操作系统',
            dataIndex: 'os',
            key: 'os',
            align: 'center'
        }, {
            title: '浏览器',
            dataIndex: 'browser',
            key: 'browser',
            align: 'center'
        }, {
            title: '描述',
            dataIndex: 'msg',
            key: 'msg',
            align: 'center'
        }, {
            title: '访问时间',
            dataIndex: 'loginTime',
            key: 'loginTime',
            align: 'center'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record: any) => (
                <div><Tag color="processing">{record.status === "0" ? "正常" : "停用"}</Tag></div>
            )
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record: any) => (
                <Space size="middle">
                    <Button onClick={() => handleDelete(record)} type="link" size="small" icon={<DeleteOutlined />}
                    >删除</Button>
                </Space>
            ),
        },
    ];

    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        logininforList(queryParams).then((res: any) => {
            setDataList(setKeyUtils(res?.rows, { key: 'infoId' }))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            setQueryParams(prevQueryParams => ({
                ...prevQueryParams,
                postCode: values.postCode,
                postName: values.postName,
                status: values.status,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }
    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        console.log("pagination", page, pageSize);
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };



    // 删除按钮
    const handleDelete = (e: Record<string, any>) => {
        const infoIds = e?.infoId || selectedRowKeys;
        confirm({
            title: '系统提示',
            content: (`是否确认删除岗位编号为"${infoIds}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                delLogininfor(infoIds).then((res: any) => {
                    if (res?.code === 200) {
                        globalMessage().info("删除成功").then(r => {
                        })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });
    }
    // 复选框选择参数赋值
    const onSelectChange = (newSelectedRowKeys:any[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // 复选框函数
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div>
                        <Form
                            form={form}
                            name="customized_form_controls"
                            style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                            layout={useResponsiveLayout("inline")}>
                            <Form.Item
                                name="ipaddr"
                                label="登录地址">
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="userName"
                                label="用户名称">
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="status"
                                label="状态">
                                <Select
                                    style={{
                                        width: 120,
                                    }}

                                    allowClear
                                    options={[
                                        {
                                            value: 0,
                                            label: '正常',
                                        }, {
                                            value: 1,
                                            label: '停用',
                                        },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                    marginRight: 20,
                                }}>
                                    查询
                                </Button>
                                <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <div>
                        {/* <Button type="primary" ghost onClick={() => {
                        handleAddClick()
                    }} style={{margin: 10}}>
                        新增
                    </Button> */}
                        <Button type="primary" ghost onClick={handleDelete} style={{ margin: 10 }}
                            disabled={selectedRowKeys.length === 0}>
                            批量删除
                        </Button>
                    </div>
                    <Table scroll={{x:'max-content'}} rowSelection={rowSelection} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange: handleTableChange,
                        onShowSizeChange: handleTableChange, // 如果需要支持 pageSize 变化
                    }} />
                </Col>
            </Row>



        </div>
    )
};
export default LoginInfoView;
